package com.gh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gh.bo.TransFlowBO;
import com.gh.common.exception.Assert;
import com.gh.common.exception.BusinessException;
import com.gh.common.result.ResponseEnum;
import com.gh.entity.Lend;
import com.gh.entity.LendItem;
import com.gh.enums.LendStatusEnum;
import com.gh.enums.TransTypeEnum;
import com.gh.hfb.FormHelper;
import com.gh.hfb.HfbConst;
import com.gh.hfb.RequestHelper;
import com.gh.mapper.LendItemMapper;
import com.gh.mapper.LendMapper;
import com.gh.mapper.UserAccountMapper;
import com.gh.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.util.LendNoUtils;
import com.gh.vo.InvestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Service
public class LendItemServiceImpl extends ServiceImpl<LendItemMapper, LendItem> implements LendItemService {

    @Autowired
    private UserBindService userBindService;

    @Autowired
    private LendMapper lendMapper;

    @Autowired
    private LendService lendService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private TransFlowService transFlowService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String commitInvest(InvestVo investVo) {
        //根据lendId查询标的信息
        Long lendId = investVo.getLendId();//标的ID
        Lend lend = lendMapper.selectById(lendId);
        //如果投资人id和lendId有数据,说明已经投资过
        LambdaQueryWrapper<LendItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LendItem::getInvestUserId, investVo.getInvestUserId());
        queryWrapper.eq(LendItem::getLendId, lend.getId());
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException("已经投资过，无法再次投资");
        }
        //标的状态必须为募资中
        Assert.isTrue(lend.getStatus().intValue() == LendStatusEnum.INVEST_RUN.getStatus().intValue(), ResponseEnum.LEND_INVEST_ERROR);
        //标的不能超卖：(已投金额 + 本次投资金额 ) >= 标的金额（超卖）
        BigDecimal sum = lend.getInvestAmount().add(new BigDecimal(investVo.getInvestAmount()));
        Assert.isTrue(sum.doubleValue() <= lend.getAmount().doubleValue(), ResponseEnum.LEND_FULL_SCALE_ERROR);
        //账户可用余额充足：当前用户的余额 >= 当前用户的投资金额（可以投资）
        Long investUserId = investVo.getInvestUserId();//获取投资人ID
        BigDecimal account = userAccountService.getAccount(investUserId);//投资账户余额
        Assert.isTrue(account.doubleValue() >= Double.parseDouble(investVo.getInvestAmount()), ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);
        //获取投资人的bindCode
        String bindCode = userBindService.getBindCodeByUserId(investUserId);
        //获取借款人的bindCode
        String benefitBindCode = userBindService.getBindCodeByUserId(lend.getUserId());
        //生成标的出借记录信息
        LendItem lendItem = new LendItem();
        String lendItemNo = LendNoUtils.getLendItemNo();//订单编号
        lendItem.setLendItemNo(lendItemNo);
        lendItem.setLendId(lend.getId());
        lendItem.setInvestUserId(investUserId);//投资用户id
        lendItem.setInvestName(investVo.getInvestName());//投资用户姓名
        lendItem.setInvestAmount(new BigDecimal(investVo.getInvestAmount()));//投资金额
        lendItem.setLendYearRate(lend.getLendYearRate());//年化利率
        lendItem.setInvestTime(new Date());//投资时间
        lendItem.setLendStartDate(lend.getLendStartDate());
        lendItem.setLendEndDate(lend.getLendEndDate());
        BigDecimal expectAmount = lendService.getInterestCount(new BigDecimal(investVo.getInvestAmount()), lend.getLendYearRate(), lend.getPeriod(), lend.getReturnMethod());
        lendItem.setExpectAmount(expectAmount);//预期收益
        lendItem.setRealAmount(new BigDecimal(0));//实际收益
        lendItem.setStatus(0);//刚刚创建投资记录，账户信息尚未修改
        baseMapper.insert(lendItem);
        //封装提交至汇付宝的参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("voteBindCode", bindCode);//投资人bindCode
        paramMap.put("benefitBindCode", benefitBindCode);//借款人bindCode
        paramMap.put("agentProjectCode", lend.getLendNo());//项目标号
        paramMap.put("agentProjectName", lend.getTitle());
        //在资金托管平台上的投资订单的唯一编号，要和lendItemNo保持一致。
        paramMap.put("agentBillNo", lendItemNo);//订单编号
        paramMap.put("voteAmt", investVo.getInvestAmount());
        paramMap.put("votePrizeAmt", "0");
        paramMap.put("voteFeeAmt", "0");
        paramMap.put("projectAmt", lend.getAmount()); //标的总金额
        paramMap.put("note", "备注");
        paramMap.put("notifyUrl", HfbConst.INVEST_NOTIFY_URL); //检查常量是否正确
        paramMap.put("returnUrl", HfbConst.INVEST_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);
        String formStr = FormHelper.buildForm(HfbConst.INVEST_URL, paramMap);
        return formStr;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String investNotify(Map<String, Object> map) {
        String agentBillNo = (String) map.get("agentBillNo");//投资编号
        //幂等性返回
        boolean isSave = transFlowService.isSaveTransFlow(agentBillNo);
        if (isSave) {
            return "success"; //幂等性返回
        }
        //余额中减去投资金额，冻结金额中增加投资金额
        String bindCode = (String) map.get("voteBindCode");
        String voteAmt = (String) map.get("voteAmt");
        userAccountMapper.updateAccount(bindCode, new BigDecimal("-" + voteAmt), new BigDecimal(voteAmt));
        //修改lendItem中的状态为已支付
        LambdaQueryWrapper<LendItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LendItem::getLendItemNo, agentBillNo);
        LendItem lendItem = baseMapper.selectOne(queryWrapper);
        lendItem.setStatus(1);
        baseMapper.updateById(lendItem);
        //修改标的记录：投资人数，已投金额
        Lend lend = lendMapper.selectById(lendItem.getLendId());
        Integer investNum = lend.getInvestNum();
        lend.setInvestNum(investNum + 1);
        lend.setInvestAmount(lend.getInvestAmount().add(new BigDecimal(voteAmt)));
        lendMapper.updateById(lend);
        //生成交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(voteAmt),
                TransTypeEnum.INVEST_LOCK,
                "投资啦"
        );
        transFlowService.saveTransFlow(transFlowBO);
        return "success";
    }

    @Override
    public List<LendItem> selectByLendId(Long lendId, Integer status) {
        LambdaQueryWrapper<LendItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LendItem::getLendId,lendId);
        queryWrapper.eq(LendItem::getStatus,status);
        List<LendItem> itemList = baseMapper.selectList(queryWrapper);
        return itemList;
    }

    @Override
    public List<LendItem> selectByLendId(Long lendId) {
        LambdaQueryWrapper<LendItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LendItem::getLendId,lendId);
        List<LendItem> itemList = baseMapper.selectList(queryWrapper);
        return itemList;
    }
}
